package com.ddwl.wallet.service;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.ddwl.common.constant.*;
import com.ddwl.common.exception.ParamException;
import com.ddwl.common.feign.api.GateApi;
import com.ddwl.common.feign.api.GoodsApi;
import com.ddwl.common.feign.api.ShopApi;
import com.ddwl.common.feign.api.UserApi;
import com.ddwl.common.util.BeanConverUtils;
import com.ddwl.common.util.MySqlUtil;
import com.ddwl.common.util.UUIDGenerator;
import com.ddwl.schema.bo.base.PageBo;
import com.ddwl.schema.bo.distr.ComputeProfitPriceBo;
import com.ddwl.schema.bo.order.DistOrderBo;
import com.ddwl.schema.bo.order.QueryUserDistOrderBo;
import com.ddwl.schema.bo.order.SubAgentDistOrderBo;
import com.ddwl.schema.bo.user.QueryUserLevelBo;
import com.ddwl.schema.bo.user.UserSearchBo;
import com.ddwl.schema.bo.wallet.QueryWalletMainReportBo;
import com.ddwl.schema.bo.wallet.QueryWalletReportBo;
import com.ddwl.schema.util.DateUtil;
import com.ddwl.schema.vo.base.PageVo;
import com.ddwl.schema.vo.dist.ComputeProfitPriceVo;
import com.ddwl.schema.vo.dist.DistVo;
import com.ddwl.schema.vo.dist.DistrConfigVo;
import com.ddwl.schema.vo.dist.UserInviteCountVo;
import com.ddwl.schema.vo.order.OrderSpuVo;
import com.ddwl.schema.vo.shop.ShopVo;
import com.ddwl.schema.vo.user.UserLevelVo;
import com.ddwl.schema.vo.user.UserVo;
import com.ddwl.schema.vo.wallet.*;
import com.ddwl.wallet.dao.OrderDao;
import com.ddwl.wallet.dao.RecordViewsDao;
import com.ddwl.wallet.dao.dto.DistOrderStatisticsDto;
import com.ddwl.wallet.dao.dto.DistOrderStatisticsQueryDto;
import com.ddwl.wallet.dao.dto.DistOrderTotalDto;
import com.ddwl.wallet.dao.dto.UserWalletMainReportDto;
import com.ddwl.wallet.dao.model.DistOrder;
import com.ddwl.wallet.dao.model.DistOrderInfo;
import com.ddwl.wallet.dao.model.RecordViews;
import com.ddwl.wallet.service.dto.UserDistConfigDto;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.Instant;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 类DistOrderService.java的实现描述：分销订单服务
 *
 * @author 27670
 * @Date :2020-07-22 14:26.
 */
@Slf4j
@Service
public class DistOrderService {

    @Resource
    private GoodsApi goodsApi;
    @Resource
    private UserApi userApi;
    @Resource
    private OrderDao orderDao;
    @Resource
    private RabbitTemplate rabbitTemplate;
    @Resource
    private RecordViewsDao recordViewsDao;
    @Value("${ddwl.dist.discount}")
    private Integer discount;
    @Resource
    private ShopApi shopApi;
    @Resource
    private GateApi gateApi;


    /**
     * 查询用户预估佣金收入
     *
     * @param bo
     * @return
     */
    public List<UserWalletReportVo> getUserPreIncome(QueryWalletReportBo bo, String userId) {
        List<UserWalletReportVo> userWalletReportVoList = new ArrayList<>();
        bo.setUserId(userId);
        //个人收益
        if (bo.getPersonalWallet() != null && bo.getPersonalWallet()) {
            UserWalletReportVo dto = new UserWalletReportVo();
            DistOrderStatisticsQueryDto query = new DistOrderStatisticsQueryDto();
            query.setType(1);
            query.setUserId(bo.getUserId());
            if (bo.getQueryCycle() == 1) {
                query.setEndTime(DateUtil.getTimesNight());
                query.setStartTime(DateUtil.getTimesMorning());
            } else if (bo.getQueryCycle() == 2) {
                query.setStartTime(DateUtil.getMondayOfThisWeek());
                query.setEndTime(DateUtil.getTimesNight());
                //query.setUserId(bo.getUserId());
            } else if (bo.getQueryCycle() == 3) {
                query.setStartTime(DateUtil.getFirstDayMonth(Instant.now()));
                query.setEndTime(DateUtil.getFirstDayAfterMonth(Instant.now()));
                //query.setUserId(bo.getUserId());
            }
            List<DistOrderStatisticsDto> list = orderDao.queryUserPreIncome(query);
            dto.setType(1);
            RecordViewsVo personViewsCount = recordViewsDao.getPersonViewsCount(query);
            if (personViewsCount != null) {
                dto.setViewsCount(personViewsCount.getCount());
            } else {
                dto.setViewsCount(0);
            }
            dto.setOrderCount(list.size());
            dto.setPreIncome(calculateAmount(list, bo.getUserId()));

            UserInviteCountVo inviteCountVo;
            if (bo.getQueryUser()) {
                inviteCountVo = userApi.getInviteCountVo(userId).getResult();
                dto.setTotal(inviteCountVo == null ? 0 : inviteCountVo.getTotal() == null ? 0 : inviteCountVo.getTotal());
                dto.setDistTotal(inviteCountVo == null ? 0 : inviteCountVo.getDistTotal() == null ? 0 : inviteCountVo.getDistTotal());
                dto.setMemberTotal(inviteCountVo == null ? 0 : inviteCountVo.getMemberTotal() == null ? 0 : inviteCountVo.getMemberTotal());
            }

            userWalletReportVoList.add(dto);
        }

        //团队收益
        if (bo.getTeamWallet() != null && bo.getTeamWallet()) {
            DistOrderStatisticsQueryDto query = new DistOrderStatisticsQueryDto();
            query.setUserId(bo.getUserId());
            query.setType(2);
            if (bo.getQueryCycle() == 1) {
                query.setEndTime(DateUtil.getTimesNight());
                query.setStartTime(DateUtil.getTimesMorning());
                //List<String>userVos=userApi.queryUserLowerIds(userId).getResult();
                //query.setUserIds(userVos);
            } else if (bo.getQueryCycle() == 2) {
                query.setStartTime(DateUtil.getMondayOfThisWeek());
                query.setEndTime(DateUtil.getTimesNight());
                //List<String>userVos=userApi.queryUserLowerIds(userId).getResult();
                //query.setUserIds(userVos);
            } else if (bo.getQueryCycle() == 3) {
                query.setStartTime(DateUtil.getFirstDayMonth(Instant.now()));
                query.setEndTime(DateUtil.getFirstDayAfterMonth(Instant.now()));
                query.setEndTime(Instant.now());
                //List<String>userVos=userApi.queryUserLowerIds(userId).getResult();
                //query.setUserIds(userVos);
            }
            List<DistOrderStatisticsDto> list = orderDao.queryUserPreIncome(query);
            UserWalletReportVo dto = new UserWalletReportVo();
            dto.setType(2);

            if (query.getUserIds() == null || query.getUserIds().size() == 0) {
                dto.setViewsCount(0);
            } else {
                RecordViewsVo personViewsCount = recordViewsDao.getTeamViewsCount(query);
                if (personViewsCount != null) {
                    dto.setViewsCount(personViewsCount.getCount());
                } else {
                    dto.setViewsCount(0);
                }
            }
            dto.setOrderCount(list.size());
            dto.setPreIncome(calculateAmount(list, bo.getUserId()));
            userWalletReportVoList.add(dto);
        }

        //区域收益
        if (bo.getRegionWallet() != null && bo.getRegionWallet()) {
            //查询订单区域经理
            List<String> list1 = userApi.getUserRegion(bo.getUserId()).getResult();
            if (list1 != null && list1.size() != 0) {
                DistOrderStatisticsQueryDto query = new DistOrderStatisticsQueryDto();
                query.setType(3);
                if (bo.getQueryCycle() == 1) {
                    query.setEndTime(DateUtil.getTimesNight());
                    query.setStartTime(DateUtil.getTimesMorning());
                    query.setUserId(bo.getUserId());
                } else if (bo.getQueryCycle() == 2) {
                    query.setStartTime(DateUtil.getMondayOfThisWeek());
                    query.setEndTime(DateUtil.getTimesNight());
                    query.setUserId(bo.getUserId());
                } else if (bo.getQueryCycle() == 3) {
                    query.setStartTime(DateUtil.getFirstDayMonth(Instant.now()));
                    query.setEndTime(DateUtil.getFirstDayAfterMonth(Instant.now()));
                    query.setEndTime(Instant.now());
                    query.setUserId(bo.getUserId());
                }
                List<DistOrderStatisticsDto> list = orderDao.queryUserPreIncome(query);
                UserWalletReportVo dto = new UserWalletReportVo();
                dto.setType(3);
                dto.setViewsCount(null);
                Set<String> set = new HashSet<>();
                if (list != null && list.size() != 0) {
                    for (DistOrderStatisticsDto dto1 : list) {
                        set.add(dto1.getOrderId());
                    }
                }
                dto.setOrderCount(set.size());
                dto.setPreIncome(calculateAmount(list, bo.getUserId()));
                userWalletReportVoList.add(dto);
            }
        }

        return userWalletReportVoList;
    }

    /**
     * 查询用户上个月预估佣金收入
     *
     * @param userId
     * @return
     */
    public BigDecimal getUserBeforeMonth(String userId) {
        return calculateAmount(orderDao.queryUserBeforeMonth(userId), userId);
    }

    /**
     * 查询用户当前月预估佣金收入
     *
     * @param userId
     * @return
     */
    public BigDecimal getUserAtMonth(String userId) {
        return calculateAmount(orderDao.queryUserAtMonth(userId), userId);
    }

    /**
     * 查询分销订单新
     *
     * @param boPageBo
     * @return
     */
    public PageVo<DistOrderVo> getDistPageNew(PageBo<QueryUserDistOrderBo> boPageBo) {
        PageHelper.startPage(boPageBo.getPage(), boPageBo.getPageSize(), MySqlUtil.orderBy(boPageBo.getSort(), false));
        PageInfo<DistOrder> info = new PageInfo(orderDao.queryDistOrder(boPageBo.getParam()));
        List<DistOrderVo> list = new ArrayList<>();
        info.getList().forEach(o -> {
            DistOrderVo vo = BeanConverUtils.convertBean(o, DistOrderVo.class);
            List<OrderSpuVo> orderSpuVos = JSON.parseArray(o.getOrderSpu(), OrderSpuVo.class);
            vo.setOrderSpuVos(orderSpuVos);
            list.add(vo);
            QueryUserDistOrderBo bo = boPageBo.getParam();
            if (bo.getType() == null) {
                bo.setType(1);
            }
            //个人分销订单
            if (bo.getType() == 1) {
                BigDecimal tradeAmount = BigDecimal.ZERO;
                if (boPageBo.getParam().getUserId().equals(o.getDistUserId()) && o.getDistType() == 1) {
                    tradeAmount = tradeAmount.add(o.getDistAmount());
                }
                vo.setTradeAmount(tradeAmount);
                //设置商品的利润
                orderSpuVos.forEach(s -> {
                    BigDecimal profitPrice = BigDecimal.ZERO;
                    if (boPageBo.getParam().getUserId().equals(o.getDistUserId()) && o.getDistType() == 1) {
                        profitPrice = profitPrice.add(s.getDistPrice());
                    }
                    s.setProfitPrice(profitPrice);
                });
                vo.setOrderSpuVos(orderSpuVos);
            } else if (bo.getType() == 2) {
                BigDecimal tradeAmount = BigDecimal.ZERO;
                if (boPageBo.getParam().getUserId().equals(o.getDistUserId()) && (o.getDistType() == 2 || o.getDistType() == 3)) {
                    tradeAmount = tradeAmount.add(o.getDistAmount());
                }
                vo.setTradeAmount(tradeAmount);
                //设置商品的利润
                orderSpuVos.forEach(s -> {
                    BigDecimal profitPrice = BigDecimal.ZERO;
                    if (boPageBo.getParam().getUserId().equals(o.getDistUserId()) && (o.getDistType() == 2 || o.getDistType() == 3)) {
                        profitPrice = profitPrice.add(s.getDistPrice());
                    }
                    s.setProfitPrice(profitPrice);
                });
                vo.setOrderSpuVos(orderSpuVos);
            } else if (bo.getType() == 3) {
                BigDecimal tradeAmount = BigDecimal.ZERO;
                if (boPageBo.getParam().getUserId().equals(o.getDistUserId()) && (o.getDistType() == 4 || o.getDistType() == 5)) {
                    tradeAmount = tradeAmount.add(o.getDistAmount());
                }
                vo.setTradeAmount(tradeAmount);
                //设置商品的利润
                orderSpuVos.forEach(s -> {
                    BigDecimal profitPrice = BigDecimal.ZERO;
                    if (boPageBo.getParam().getUserId().equals(o.getDistUserId()) && (o.getDistType() == 4 || o.getDistType() == 5)) {
                        profitPrice = profitPrice.add(s.getDistPrice());
                    }
                    s.setProfitPrice(profitPrice);
                });
                vo.setOrderSpuVos(orderSpuVos);
            }
        });
        return new PageVo<>(info.getTotal(), boPageBo.getPage(), boPageBo.getPageSize(), list);
    }

    /**
     * 查询分销订单后台
     *
     * @param boPageBo
     * @return
     */
    public PageVo<DistOrderVo> getDistPageForConsole(PageBo<QueryUserDistOrderBo> boPageBo) {
        PageHelper.startPage(boPageBo.getPage(), boPageBo.getPageSize(), MySqlUtil.orderByNotUnderlineCase(boPageBo.getSort(), boPageBo.isAsc()));
        PageInfo<DistOrder> info = new PageInfo(orderDao.queryDistOrderForConsole(boPageBo.getParam()));
        DistOrderTotalDto distOrderTotalDto = orderDao.queryDistOrderTotalForConsole(boPageBo.getParam());
        List<DistOrderVo> list = BeanConverUtils.convertBeanList(info.getList(), DistOrderVo.class);
        list.forEach(distOrderVo -> distOrderVo.setOrderSpuVos(JSON.parseArray(distOrderVo.getOrderSpu(), OrderSpuVo.class)));
        PageVo<DistOrderVo> distOrderVoPageVo = new PageVo<>(info.getTotal(), boPageBo.getPage(), boPageBo.getPageSize(), list);
        distOrderVoPageVo.setStatistics(distOrderTotalDto);
        return distOrderVoPageVo;
    }


    public void confirmOrder(String orderId, Instant confirmTime) {
        orderDao.confirmOrder(orderId, confirmTime);
    }


    /**
     * 生成店铺佣金
     */
    public DistOrder createShopDist(DistOrderInfo orderInfoVo) {
        DistOrder distOrder = BeanConverUtils.convertBean(orderInfoVo, DistOrder.class);
        ShopVo shopVo = shopApi.getShopForApi(orderInfoVo.getShopId()).getResult();
        distOrder.setDistUserId(shopVo.getUserId());
        distOrder.setDistUserName(shopVo.getUserName());
        distOrder.setDistUserTel(shopVo.getUserTel());
        distOrder.setDistType(DistTypeEnum.SHOP.getType());
        distOrder.setIsAfterSale(0);
        List<DistOrder> distOrders = orderDao.queryDistOrderListByOrderId(orderInfoVo.getOrderId());
        if (!CollectionUtils.isEmpty(distOrders)) {
            //分润金额
            BigDecimal tradeAmount = distOrders.stream().map(DistOrder::getDistAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
            distOrder.setTradeAmount(tradeAmount);
            distOrder.setDistAmount(orderInfoVo.getOrderPrice().subtract(tradeAmount));
        } else {
            distOrder.setTradeAmount(BigDecimal.ZERO.stripTrailingZeros());
            distOrder.setDistAmount(orderInfoVo.getOrderPrice());
        }
        orderDao.insert(distOrder);
        return distOrder;
    }

    //异步 同步分销单
    @Async
    public void updateUserDist(List<DistOrder> distOrderList) {
        List<DistOrderBo> distOrderBos = BeanConverUtils.convertBeanList(distOrderList, DistOrderBo.class);
        userApi.updateUserDistStatistical(distOrderBos);
    }

    // 计算用户预估收益
    private BigDecimal calculateAmount(List<DistOrderStatisticsDto> distOrderStatisticsDtos, String userId) {
        BigDecimal amount = BigDecimal.ZERO;
        if (CollectionUtils.isEmpty(distOrderStatisticsDtos)) {
            return amount;
        }
        for (DistOrderStatisticsDto statisticsDto : distOrderStatisticsDtos) {
            if (userId.equals(statisticsDto.getDistUserId()) && (statisticsDto.getIsAfterSale() == null || statisticsDto.getIsAfterSale() == 0)) {
                amount = amount.add(statisticsDto.getDistAmount());
            }
            //区域经理已经单独生成一条,所以不用在加入
/*            if(userId.equals(statisticsDto.getRegionUserId())){
                bigDecimal = bigDecimal.add(statisticsDto.getRegionAmount());
            }*/
        }
        return amount;
    }


    /**
     * 查询订单分销信息
     *
     * @param orderId
     */
    public List<DistVo> getDistOrder(String orderId) {
        ParamException.isBlank(orderId, "订单id为空");
        DistOrder distOrder = new DistOrder();
        distOrder.setOrderId(orderId);
        List<DistVo> list = BeanConverUtils.convertBeanList(orderDao.select(distOrder), DistVo.class);
        for (DistVo distVo : list) {
            if (StringUtils.hasText(distVo.getDistUserId())) {
                if (distVo.getDistUserId().equals("-1")) {
                    distVo.setDistUserName("多典总公司");
                    //distVo.setDistUserAvatar("");
                } else {
                    UserVo userVo = userApi.getProfile(distVo.getDistUserId()).getResult();
                    if (userVo != null) {
                        distVo.setDistUserName(userVo.getNickname());
                        distVo.setDistUserAvatar(userVo.getAvatar());
                    }
                }
            }
        }
        //过滤店铺佣金
        return list.stream().filter(distVo -> !DistTypeEnum.SHOP.getType().equals(distVo.getDistType())).collect(Collectors.toList());
    }


    /**
     * 记录点击数
     *
     * @param source
     */
    public void recordViews(String source) {
        //记录点击数
        if (!StrUtil.isBlank(source)) {
            rabbitTemplate.convertAndSend(RabbitMqConstants.RECORD_VIEWS_COUNT, source);
        }
    }


    /**
     * 记录点击数
     *
     * @param source
     */
    public void recordViewsCount(String source) {
        UserVo userVo = userApi.getProfile(source).getResult();
        if (userVo != null) {
            RecordViews recordViews = new RecordViews();
            recordViews.setUserId(userVo.getId());
            recordViews.setRecordDate(DateUtil.formatDate(Instant.now()));
            RecordViews record = recordViewsDao.selectOne(recordViews);
            RecordViews update = new RecordViews();
            if (record != null) {//同一天同一用户
                update.setId(record.getId());
                update.setCount(record.getCount() + 1);
                recordViewsDao.updateByPrimaryKeySelective(update);
            } else {
                update.setCount(1);
                update.setRecordDate(DateUtil.formatDate(Instant.now()));
                update.setUserId(userVo.getId());
                update.setSource(source);
                update.setImmediateSuperior(userVo.getImmediateSuperior());
                update.setIndirectSuperior(userVo.getIndirectSuperior());
                recordViewsDao.insert(update);
            }
        }
    }

    public List<DistOrder> queryByUserId(String userId) {
        DistOrder entity = new DistOrder();
        entity.setDistUserId(userId);
        return orderDao.select(entity);
    }

    public void correctDistOrder(String fxUserId, DistOrder distOrder) {
        orderDao.deleteById(distOrder.getId());
        distOrder.setId(UUIDGenerator.getShortUUID());
        distOrder.setDistUserId(fxUserId);
        distOrder.setSource(fxUserId);
        orderDao.copyInsert(distOrder);
    }

    public UserWalletMainReportVo walletMainReport(String userId) {
        QueryWalletMainReportBo bo = new QueryWalletMainReportBo();
        bo.setUserId(userId);
        //查询总收益
        UserWalletMainReportDto userWalletMainReportDto = orderDao.queryWalletMainReport(bo);
        //查询未结算金额
        bo.setDistOrderStatus(DistConstant.DistOrderStatus.CLOSE.getCode());
        UserWalletMainReportDto userWalletMainReportDto2 = orderDao.queryWalletMainReport(bo);
        UserWalletMainReportVo vo = new UserWalletMainReportVo();
        if (userWalletMainReportDto == null) {
            vo.setTotalAmount(BigDecimal.ZERO);
        } else {
            vo.setTotalAmount(userWalletMainReportDto.getAmount());
        }
        if (userWalletMainReportDto2 == null) {
            vo.setUnClearAmount(BigDecimal.ZERO);
        } else {
            vo.setUnClearAmount(userWalletMainReportDto2.getAmount());
        }
        return vo;
    }

    public void updateDistOrderUser() {
        List<DistOrder> distOrderList = orderDao.selectAll();
        PageBo<UserSearchBo> pageBo = new PageBo<>();
        UserSearchBo bo = new UserSearchBo();
        pageBo.setParam(bo);
        pageBo.setPageSize(6000);
        List<UserVo> userVos = userApi.queryUser(pageBo).getResult().getData();
        List<DistOrder> orderList = new ArrayList<>();
        //匹配分销员id
        for (DistOrder distOrder : distOrderList) {
            for (UserVo userVo : userVos) {
                if (distOrder.getDistUserId().equals(userVo.getId())) {
                    DistOrder dist = new DistOrder();
                    dist.setId(distOrder.getId());
                    dist.setDistUserName(userVo.getNickname());
                    dist.setDistUserTel(userVo.getMobile());
                    orderList.add(dist);
                    break;
                }
            }
        }
        orderDao.batchUpdateUser(orderList);
    }

    public void updateDistRecordUser() {
        List<RecordViews> recordViews = recordViewsDao.selectAll();
        PageBo<UserSearchBo> pageBo = new PageBo<>();
        UserSearchBo bo = new UserSearchBo();
        pageBo.setParam(bo);
        pageBo.setPageSize(6000);
        List<UserVo> userVos = userApi.queryUser(pageBo).getResult().getData();
        List<UserVo> collect = userVos.stream().filter(o -> !(o.getImmediateSuperior() == null && o.getIndirectSuperior() == null)).collect(Collectors.toList());
        List<RecordViews> recordViewsList = new ArrayList<>();
        //匹配分销员id
        for (RecordViews recordViews1 : recordViews) {
            for (UserVo userVo : collect) {
                if (recordViews1.getUserId().equals(userVo.getId())) {
                    RecordViews record = new RecordViews();
                    record.setId(recordViews1.getId());
                    record.setIndirectSuperior(userVo.getIndirectSuperior());
                    record.setImmediateSuperior(userVo.getImmediateSuperior());
                    recordViewsList.add(record);
                    break;
                }
            }
        }
        recordViewsDao.batchUpdateRecord(recordViewsList);
    }


    /**
     * 商品分润信息
     */
    private List<ComputeProfitPriceVo> getProfitPrice(List<OrderSpuVo> orderSpuVos) {
        List<ComputeProfitPriceVo> profitPriceVos = new ArrayList<>();
        List<ComputeProfitPriceBo> computeProfitPriceVos = new ArrayList<>();
        if (!CollectionUtils.isEmpty(orderSpuVos)) {
            orderSpuVos.forEach(orderSpuVo -> {
                ComputeProfitPriceBo computeProfitPriceBo = new ComputeProfitPriceBo();
                computeProfitPriceBo.setCategoryId(orderSpuVo.getCategoryId());
                computeProfitPriceBo.setSkuId(orderSpuVo.getSkuId());
                computeProfitPriceBo.setItemId(orderSpuVo.getItemId());
                computeProfitPriceBo.setPrice(orderSpuVo.getRealPrice());
                computeProfitPriceBo.setId(orderSpuVo.getId());
                computeProfitPriceVos.add(computeProfitPriceBo);
            });
            profitPriceVos = goodsApi.computeProfitPrice(computeProfitPriceVos).getResult();
        }
        profitPriceVos = profitPriceVos.stream().filter(o -> o.getProfitPrice() != null && o.getProfitPrice().compareTo(BigDecimal.ZERO) > 0).collect(Collectors.toList());
        return profitPriceVos;
    }


    /**
     * 获取商品的分润金额
     *
     * @param orderInfoVo
     * @return
     */
    private List<OrderSpuVo> getOrderSpuDist(DistOrderInfo orderInfoVo) {
        //砍价单不生成分销
        if (orderInfoVo.getOrderType() != null && OrderEnum.OrderWay.BARGAIN.getCode().equals(orderInfoVo.getOrderType())) {
            return new ArrayList<>();
        }
        //秒杀单不生成分销
        if (orderInfoVo.getOrderType() != null && OrderEnum.OrderWay.SEC_KILL.getCode().equals(orderInfoVo.getOrderType())) {
            return new ArrayList<>();
        }
        return JSON.parseArray(orderInfoVo.getOrderSpu(), OrderSpuVo.class);
    }

    /**
     * 解析创建分销订单
     *
     * @param orderInfoVo
     * @return
     */
    public List<DistOrder> saveDistOrderList(DistOrderInfo orderInfoVo,Integer charityFlag) {
        //查询参与分佣的用户的佣金金额
        List<UserDistConfigDto> userDistConfigDtos = getUserDistUser(orderInfoVo,charityFlag);
        //查询商品的佣金金额
        List<OrderSpuVo> orderSpuVos = getOrderSpuDist(orderInfoVo);
        //生成分销单信息
        List<DistOrder> orderList = new ArrayList<>();
        userDistConfigDtos.stream().filter(userDistConfigDto -> userDistConfigDto.getRatio().compareTo(BigDecimal.ZERO) > 0).forEach(userDistConfigDto -> {
            orderSpuVos.stream().filter(orderSpuVo -> orderSpuVo.getProfitPrice() != null).filter(orderSpuVo -> orderSpuVo.getProfitPrice().compareTo(BigDecimal.ZERO) > 0).forEach(orderSpuVo -> {
                orderList.add(warpDistOrder(BeanConverUtils.convertBean(orderInfoVo, DistOrder.class), userDistConfigDto, orderSpuVo));
            });
        });
        // 公益账户发送公益金
        UserDistConfigDto userDistConfigDto = userDistConfigDtos.stream().filter(dto -> DistTypeEnum.CHARITY.getType().equals(dto.getType())).findFirst().orElse(null);
        if (null != userDistConfigDto) {
            DistOrder distOrder = BeanConverUtils.convertBean(orderInfoVo, DistOrder.class);
            orderSpuVos.stream().forEach(orderSpuVo -> {
                distOrder.setDistAmount(BigDecimal.ONE.add(RandomUtil.randomBigDecimal()).multiply(new BigDecimal(orderSpuVo.getSkuQty())).setScale(2, RoundingMode.HALF_UP));
                orderList.add(warpDistOrder(distOrder, userDistConfigDto, orderSpuVo));
            });
        }
        orderDao.insertList(orderList);
        return orderList;
    }

    private DistOrder warpDistOrder(DistOrder distOrder, UserDistConfigDto dto, OrderSpuVo orderSpuVo) {
        distOrder.setDistUserId(dto.getUserId());
        distOrder.setDistUserName(dto.getUserName());
        distOrder.setDistUserTel(dto.getMobile());
        distOrder.setSpuId(orderSpuVo.getId());
        if (null == distOrder.getDistAmount()) {
            distOrder.setDistAmount(orderSpuVo.getProfitPrice().multiply(new BigDecimal(orderSpuVo.getSkuQty())).multiply(dto.getRatio()).divide(new BigDecimal("100"), 2, RoundingMode.HALF_UP));
        }
        distOrder.setDistType(dto.getType());
        distOrder.setOrderPrice(orderSpuVo.getRealPrice().multiply(new BigDecimal(orderSpuVo.getSkuQty())));
        distOrder.setTradeAmount(orderSpuVo.getProfitPrice().multiply(new BigDecimal(orderSpuVo.getSkuQty())));
        if (DistTypeEnum.PERSONAL_AGENT_PROFIT.getType().equals(dto.getType())
                ||DistTypeEnum.STORE_AGENT_PROFIT.getType().equals(dto.getType())
                ||DistTypeEnum.ZONE_AGENT_PROFIT.getType().equals(dto.getType())) {
            distOrder.setTradeAmount(distOrder.getOrderPrice().subtract(orderSpuVo.getProfitPrice().multiply(new BigDecimal(orderSpuVo.getSkuQty()))));
        }
        orderSpuVo.setDistPrice(distOrder.getDistAmount());
        distOrder.setOrderSpu(JSON.toJSONString(Arrays.asList(orderSpuVo)));
        distOrder.setIsAfterSale(0);
        return distOrder;
    }

    /**
     * 查询参与分佣的用户
     *
     * @param orderInfoVo
     * @return
     */
    private List<UserDistConfigDto> getUserDistUser(DistOrderInfo orderInfoVo,Integer charityFlag) {
        List<UserDistConfigDto> userDistConfigDtos = new ArrayList<>();
        //商户订单佣金
        if (StringUtils.hasText(orderInfoVo.getShopId()) && GoodsEnum.CategoryTypeEnum.RETAIL.getCode().equals(orderInfoVo.getPlatformTag())) {
            userDistConfigDtos = getShopOrderUserDistConfig(orderInfoVo);
            //平台普通订单佣金
        } else if (DistConstant.DistrConfigType.PRODUCT.getCode().equals(orderInfoVo.getType())) {
            userDistConfigDtos = getPlatformOrderUserDistConfig(orderInfoVo,charityFlag);
            //平台开通商户订单
        } else if (DistConstant.DistrConfigType.SHOP.getCode().equals(orderInfoVo.getType())) {
            String result = gateApi.getSettingVal(GateEnum.DictionaryTag.TAG_SYSTEM.name(), GateEnum.DictionaryField.SHOP_JOIN_DIST.name()).getResult();
            if (null != result && Boolean.getBoolean(result)) {
                userDistConfigDtos = getShopThresholdOrderUserDistConfig(orderInfoVo);
            }
        } else if (DistConstant.DistrConfigType.AGENT.getCode().equals(orderInfoVo.getType())) {
            userDistConfigDtos = getUpgradeAgentOrderUserDistConfig(orderInfoVo);
        }
        return userDistConfigDtos;
    }

    private UserDistConfigDto getRegionUsetDist(DistOrderInfo orderInfoVo, BigDecimal regionRate, UserVo userVo) {
        UserVo regionUserVo = userApi.getRegionUser(orderInfoVo.getOrderRegion()).getResult();

        //让利给总代
        if (discount.equals(DistEnum.Discount.DISCOUNT.getCode())) {
            //如果当前区域没有代理或者 当前区域合伙人是公司 都直接给当前用户的总代理
            if ((regionUserVo == null || Byte.valueOf("1").equals(regionUserVo.getCompanyAccount()))) {
                if (userVo != null && StrUtil.isNotEmpty(userVo.getTopAgent())) {
                    regionUserVo = userApi.getProfile(userVo.getTopAgent()).getResult();
                }
            }
        } else {
            //不让利的情况没找到区域合伙人直接给公司
            if (regionUserVo == null) {
                UserSearchBo userSearchBo = new UserSearchBo();
                userSearchBo.setCompanyAccount(1);
                PageBo<UserSearchBo> pageBo = new PageBo<>();
                pageBo.setParam(userSearchBo);
                regionUserVo = userApi.queryUser(pageBo).getResult().getData().get(0);
            }
        }
        if (regionUserVo == null) {
            return null;
        }
        return getUserDistConfigDto(regionUserVo, regionRate, DistTypeEnum.REGION);
    }

    /**
     * 获取平台订参与分佣人员的分佣信息
     *
     * @param orderInfoVo
     * @return
     */
    private List<UserDistConfigDto> getPlatformOrderUserDistConfig(DistOrderInfo orderInfoVo,Integer charityFlag) {
        List<UserDistConfigDto> userWalletChangeDos = new ArrayList<>();
        //获取分佣配置
        DistrConfigVo distrConfigVo = userApi.getDistConfig(DistConstant.DistrConfigType.PRODUCT.getCode()).getResult();
        //先根据下单用户来如果当前下单用户不是分销员就根据分享Id来
//        UserVo userVo = userApi.getProfile(orderInfoVo.getOrderUserId()).getResult();
//        if(userVo==null&&StrUtil.isNotBlank(orderInfoVo.getSource())){
//            userVo = userApi.getProfile(orderInfoVo.getSource()).getResult();
//        }
        UserVo userVo = userApi.getProfile(orderInfoVo.getSource()).getResult();
        //生成区域佣金
        UserDistConfigDto regionDist = getRegionUsetDist(orderInfoVo, distrConfigVo.getRegionRate(), userVo);
        if (regionDist != null) {
            userWalletChangeDos.add(regionDist);
        }
        //如果分销员信息不为空生成分销员信息
        if (userVo != null) {
            //生成个人佣金 个人默认是三级代理
            UserDistConfigDto personal = getUserDistConfigDto(userVo, distrConfigVo.getThreeAgentRate(), DistTypeEnum.PERSONAL);
            userWalletChangeDos.add(personal);
            //生成总代理佣金
            if (StrUtil.isNotBlank(userVo.getTopAgent())) {
                UserVo topUser = userApi.getProfile(userVo.getTopAgent()).getResult();
                userWalletChangeDos.add(getUserDistConfigDto(topUser, distrConfigVo.getTopAgentRate(), DistTypeEnum.TOP));
            } else if (StrUtil.isNotBlank(userVo.getRegionId())) {
                UserVo topUser = userApi.getTopUserByRegionId(userVo.getRegionId()).getResult();
                if (null != topUser) {
                    userWalletChangeDos.add(getUserDistConfigDto(topUser, distrConfigVo.getTopAgentRate(), DistTypeEnum.TOP));
                }
            }
            //直接上级佣金
            UserDistConfigDto immediate = null;
            //间接上级佣金
            UserDistConfigDto indirect = null;
            //生成二级代理佣金
            List<UserLevelVo> userLevelVos = userApi.queryUserLevel(new QueryUserLevelBo()).getResult();
            if (StrUtil.isNotBlank(userVo.getImmediateSuperior())) {
                UserVo immediateUser = userApi.getProfile(userVo.getImmediateSuperior()).getResult();
                immediate = getUserDistConfigDto(immediateUser, getImmediateRate(userLevelVos, immediateUser), DistTypeEnum.IMMEDIATE);
                userWalletChangeDos.add(immediate);
            }
            //生成一级代理佣金  如果没有一级代理一级代理的钱给个人
            if (StrUtil.isNotBlank(userVo.getIndirectSuperior())) {
                UserVo indirectSuperior = userApi.getProfile(userVo.getIndirectSuperior()).getResult();
                indirect = getUserDistConfigDto(indirectSuperior, distrConfigVo.getOneAgentRate(), DistTypeEnum.INDIRECT);
                userWalletChangeDos.add(indirect);
            }
            //如果没有二级代理二级代理和一级代理的钱给个人
            if (immediate == null) {
                personal.setRatio(personal.getRatio().add(getImmediateRate(userLevelVos, userVo)).add(distrConfigVo.getOneAgentRate()));
                //如果没有一级代理一级代理的钱给二级代理
            } else if (indirect == null) {
                immediate.setRatio(immediate.getRatio().add(distrConfigVo.getOneAgentRate()));
            }
        }
        if (BaseEnum.StatusEnum.ENABLE.getCode().equals(charityFlag)) {
            UserVo vo = new UserVo();
            vo.setId(UserEnum.AccountEnum.CHARITY_ACCOUNT.getId());
            vo.setMobile(UserEnum.AccountEnum.CHARITY_ACCOUNT.getMobile());
            vo.setNickname(UserEnum.AccountEnum.CHARITY_ACCOUNT.getName());
            UserDistConfigDto userDistConfigDto = getUserDistConfigDto(vo, BigDecimal.ZERO, DistTypeEnum.CHARITY);
            userWalletChangeDos.add(userDistConfigDto);
        }
        return userWalletChangeDos;
    }

    private UserDistConfigDto getUserDistConfigDto(UserVo disUser, BigDecimal ratio, DistTypeEnum distTypeEnum) {
        Integer type = distTypeEnum.getType();
        if (DistTypeEnum.AGENT_ITEM_PROFIT.getType().equals(distTypeEnum.getType())) {
            if (UserEnum.ProfitLevelEnum.PERSONAL.getLevel().equals(disUser.getProfitLevel())) {
                type = DistTypeEnum.PERSONAL_AGENT_PROFIT.getType();
            }
            if (UserEnum.ProfitLevelEnum.STORE.getLevel().equals(disUser.getProfitLevel())) {
                type = DistTypeEnum.STORE_AGENT_PROFIT.getType();
            }
            if (UserEnum.ProfitLevelEnum.ZONE.getLevel().equals(disUser.getProfitLevel())) {
                type = DistTypeEnum.ZONE_AGENT_PROFIT.getType();
            }
        }
        return UserDistConfigDto.builder()
                .userId(disUser.getId())
                .mobile(disUser.getMobile())
                .userName(disUser.getNickname())
                .ratio(ratio)
                .type(type)
                .build();
    }

    /**
     * 获取参与开店金额分佣的人员
     *
     * @param orderInfoVo
     * @return
     */
    private List<UserDistConfigDto> getShopThresholdOrderUserDistConfig(DistOrderInfo orderInfoVo) {
        List<UserDistConfigDto> userWalletChangeDtos = new ArrayList<>();
        //先根据下单用户来如果当前下单用户不是分销员就根据分享Id来
        UserVo userVo = userApi.getProfile(orderInfoVo.getOrderUserId()).getResult();
        //个人佣金
        UserVo immediateUser = null;
        //如果分销员信息不为空生成分销员信息
        if (userVo != null) {
            //生成二级代理佣金  如果没有二级代理二级代理的钱给个人
            if (StrUtil.isNotBlank(userVo.getImmediateSuperior())) {
                immediateUser = userApi.getProfile(userVo.getImmediateSuperior()).getResult();
                UserDistConfigDto immediate = getUserDistConfigDto(immediateUser, new BigDecimal("60"), DistTypeEnum.PERSONAL);
                userWalletChangeDtos.add(immediate);
            }
        }
        UserVo regionUserVo = userApi.getRegionUser(orderInfoVo.getOrderRegion()).getResult();
        if (regionUserVo != null) {
            //生成区域佣金
            UserDistConfigDto regionDist = getUserDistConfigDto(regionUserVo, new BigDecimal("40"), DistTypeEnum.REGION);
            userWalletChangeDtos.add(regionDist);
            //如果区域经理为空个人拿全部佣金
        } else if (regionUserVo == null && immediateUser != null) {
            UserDistConfigDto immediate = userWalletChangeDtos.get(0);
            immediate.setRatio(new BigDecimal("100"));
        }
        return userWalletChangeDtos;
    }

    /**
     * 获取用户代理费分佣的人员
     *
     * @param orderInfoVo
     * @return
     */
    private List<UserDistConfigDto> getUpgradeAgentOrderUserDistConfig(DistOrderInfo orderInfoVo) {
        List<UserDistConfigDto> userWalletChangeDtos = new ArrayList<>();
        UserVo userVo = userApi.getUserById(orderInfoVo.getOrderUserId()).getResult();
        if (userVo != null) {
            //代理费佣金全部给直接上级
            if (StrUtil.isNotBlank(userVo.getImmediateSuperior())) {
                UserVo immediateUser = userApi.getProfile(userVo.getImmediateSuperior()).getResult();
                UserDistConfigDto immediate = getUserDistConfigDto(immediateUser, new BigDecimal("100"), DistTypeEnum.USER_AGENT_PROFIT);
                userWalletChangeDtos.add(immediate);
            }
        }
        return userWalletChangeDtos;
    }

    /**
     * 获取店铺订单参与分佣人员
     *
     * @param orderInfoVo
     * @return
     */
    private List<UserDistConfigDto> getShopOrderUserDistConfig(DistOrderInfo orderInfoVo) {
        List<UserDistConfigDto> userWalletChangeDtos = new ArrayList<>();
        //先根据下单用户来如果当前下单用户不是分销员就根据分享Id来
        UserVo userVo = userApi.getProfile(orderInfoVo.getOrderUserId()).getResult();
        //个人默认拿45
        if (userVo != null) {
            UserDistConfigDto personal = getUserDistConfigDto(userVo, new BigDecimal("45"), DistTypeEnum.PERSONAL);
            userWalletChangeDtos.add(personal);
        }
        //分享人佣金(分享人和下单人如果是同一个人佣金只算一份)
        if (StrUtil.isNotBlank(orderInfoVo.getSource())) {
            UserVo source = userApi.getProfile(orderInfoVo.getSource()).getResult();
            if (source != null && !userVo.getId().equals(source.getId())) {
                UserDistConfigDto sourceDist = getUserDistConfigDto(source, new BigDecimal("45"), DistTypeEnum.PERSONAL);
                userWalletChangeDtos.add(sourceDist);
            }
        }
        //邀请店铺开店的人拿佣金
        ShopVo shopVo = shopApi.getShopForApi(orderInfoVo.getShopId()).getResult();
        UserVo shopUser = userApi.getProfile(shopVo.getUserId()).getResult();
        if (StrUtil.isNotBlank(shopUser.getImmediateSuperior())) {
            UserVo immediateUser = userApi.getProfile(shopUser.getImmediateSuperior()).getResult();
            if (immediateUser != null) {
                UserDistConfigDto immediateDist = getUserDistConfigDto(immediateUser, new BigDecimal("10"), DistTypeEnum.IMMEDIATE);
                userWalletChangeDtos.add(immediateDist);
            }
        }
        return userWalletChangeDtos;
    }

    private BigDecimal getImmediateRate(List<UserLevelVo> userLevelVos, UserVo userVo) {
        //用户直接上级佣金根据用户等级来
        for (UserLevelVo userLevelVo : userLevelVos) {
            if (userVo.getUserLevelId().equals(userLevelVo.getId())) {
                return userLevelVo.getDistRate();
            }
        }
        return BigDecimal.ZERO;
    }

    /**
     * 代理商品订单保存分润信息
     * @param orderInfo
     * @return
     */
    public List<DistOrder> saveAgentOrderList(DistOrderInfo orderInfo) {
        //查询参与分润的用户的利润
        List<UserDistConfigDto> userDistConfigDtos;

        String shopId = gateApi.getSettingVal(GateEnum.DictionaryTag.TAG_SYSTEM.name(), GateEnum.DictionaryField.SYSTEM_SHOP.name()).getResult();
        //公司店铺下单和代理用户店铺下单，按照不同的规则进行分润
        if (shopId.equals(orderInfo.getShopId())) {
            userDistConfigDtos = getSystemShopAgentOrderUserDistConfig(orderInfo);
        }else{
            userDistConfigDtos = getAgentOrderUserDistConfig(orderInfo);
        }
        //查询商品信息
        List<OrderSpuVo> orderSpuVos = getOrderSpuDist(orderInfo);
        //生成分销单信息
        List<DistOrder> orderList = new ArrayList<>();
        userDistConfigDtos.stream().filter(userDistConfigDto -> userDistConfigDto.getRatio().compareTo(BigDecimal.ZERO) > 0).forEach(userDistConfigDto -> {
            DistOrder distOrder = BeanConverUtils.convertBean(orderInfo, DistOrder.class);
            orderSpuVos.stream().forEach(orderSpuVo -> {
                BigDecimal profit = null == orderSpuVo.getProfitPrice() ? BigDecimal.ZERO : orderSpuVo.getProfitPrice();
                distOrder.setDistAmount(orderSpuVo.getRealPrice().subtract(profit).multiply(new BigDecimal(orderSpuVo.getSkuQty())).multiply(userDistConfigDto.getRatio()).setScale(2,RoundingMode.HALF_UP));
                orderList.add(warpDistOrder(distOrder, userDistConfigDto, orderSpuVo));
            });
        });
        orderDao.insertList(orderList);
        return orderList;
    }

    /**
     * 获取代理商分润配置
     * @param orderInfoVo
     * @return
     */
    private List<UserDistConfigDto> getAgentOrderUserDistConfig(DistOrderInfo orderInfoVo) {
        List<UserDistConfigDto> userWalletChangeDos = new ArrayList<>();
        UserVo userVo = userApi.getUserById(orderInfoVo.getSource()).getResult();
        if (null != userVo) {
            Map<String, String> settingMap = gateApi.getSettingByTag(GateEnum.DictionaryTag.TAG_PROFIT.name()).getResult();
            if(CollectionUtils.isEmpty(settingMap)) {
                return userWalletChangeDos;
            }
            //店代拿百分之40
            BigDecimal shopRate = new BigDecimal(settingMap.get(GateEnum.DictionaryField.PROFIT_STORE.name()));
            UserDistConfigDto shop = getUserDistConfigDto(userVo, shopRate, DistTypeEnum.STORE_AGENT_PROFIT);
            userWalletChangeDos.add(shop);
            if (StringUtils.hasText(userVo.getImmediateSuperior())) {
                UserVo immediateUser = userApi.getUserById(userVo.getImmediateSuperior()).getResult();
                //区代拿百分之8
                BigDecimal agentRate = new BigDecimal(settingMap.get(GateEnum.DictionaryField.PROFIT_AGENT.name()));
                UserDistConfigDto agent = getUserDistConfigDto(immediateUser, agentRate, DistTypeEnum.ZONE_AGENT_PROFIT);
                userWalletChangeDos.add(agent);
            }
        }
        return userWalletChangeDos;
    }

    /**
     * 获取系统店铺代代理商品理商分润配置
     * @param orderInfoVo
     * @return
     */
    private List<UserDistConfigDto> getSystemShopAgentOrderUserDistConfig(DistOrderInfo orderInfoVo) {
        List<UserDistConfigDto> userDistConfigDtos = new ArrayList<>();
        UserVo userVo = userApi.getUserById(orderInfoVo.getSource()).getResult();
        if (null != userVo) {
            Map<String, String> settingMap = gateApi.getSettingByTag(GateEnum.DictionaryTag.TAG_SYSTEM_SHOP_AGENT_PROFIT.name()).getResult();
            if(!CollectionUtils.isEmpty(settingMap)) {
                //如果是代理
                calculateProfit(userDistConfigDtos, userVo, settingMap);
                //如果是普通用户，就查询他的直接上级
                if (UserEnum.ProfitLevelEnum.NORMAL.getLevel().equals(userVo.getProfitLevel())) {
                    if (StringUtils.hasText(userVo.getImmediateSuperior())) {
                        UserVo immediateUser = userApi.getUserById(userVo.getImmediateSuperior()).getResult();
                        if (!UserEnum.ProfitLevelEnum.NORMAL.getLevel().equals(immediateUser.getProfitLevel())) {
                            calculateProfit(userDistConfigDtos,immediateUser,settingMap);
                        }
                    }
                }
            }
        }
        return userDistConfigDtos;
    }

    private void calculateProfit(List<UserDistConfigDto> userDistConfigDtos, UserVo userVo, Map<String, String> settingMap) {
        BigDecimal personalRate = new BigDecimal(settingMap.get(GateEnum.DictionaryField.SYSTEM_SHOP_PERSONAL_AGENT_PROFIT.name()));
        BigDecimal storeRate = new BigDecimal(settingMap.get(GateEnum.DictionaryField.SYSTEM_SHOP_STORE_AGENT_PROFIT.name()));
        BigDecimal zoneRate = new BigDecimal(settingMap.get(GateEnum.DictionaryField.SYSTEM_SHOP_ZONE_AGENT_PROFIT.name()));
        //如果是区代，拿全部分润
        if (UserEnum.ProfitLevelEnum.ZONE.getLevel().equals(userVo.getProfitLevel())) {
            UserDistConfigDto agent = getUserDistConfigDto(userVo, personalRate.add(storeRate).add(zoneRate).setScale(2), DistTypeEnum.AGENT_ITEM_PROFIT);
            userDistConfigDtos.add(agent);
        }
        //如果是店代，拿个代和店代的分润，然后查询上级，如果有上级则上级拿区代的分润
        if (UserEnum.ProfitLevelEnum.STORE.getLevel().equals(userVo.getProfitLevel())) {
            UserDistConfigDto agent = getUserDistConfigDto(userVo, personalRate.add(storeRate).setScale(2), DistTypeEnum.AGENT_ITEM_PROFIT);
            userDistConfigDtos.add(agent);
            if (StringUtils.hasText(userVo.getImmediateSuperior())) {
                UserVo immediateUser = userApi.getUserById(userVo.getImmediateSuperior()).getResult();
                if (null != immediateUser) {
                    perfectingDistConfig(userDistConfigDtos, immediateUser, settingMap,0);
                }
            }
        }
        //如果是个代，拿个代的分润，然后查询上级，如果上级是店代，则上级拿店代的分润，上上级拿区代分润，如果上级是区代，则上级拿区代和店代的分润
        if (UserEnum.ProfitLevelEnum.PERSONAL.getLevel().equals(userVo.getProfitLevel())) {
            UserDistConfigDto agent = getUserDistConfigDto(userVo, personalRate, DistTypeEnum.AGENT_ITEM_PROFIT);
            userDistConfigDtos.add(agent);

            if (StringUtils.hasText(userVo.getImmediateSuperior())) {
                UserVo immediateUser = userApi.getUserById(userVo.getImmediateSuperior()).getResult();
                if (null != immediateUser) {
                    if (UserEnum.ProfitLevelEnum.STORE.getLevel().equals(immediateUser.getProfitLevel())){
                        perfectingDistConfig(userDistConfigDtos,immediateUser, settingMap,0);
                    }
                    if (UserEnum.ProfitLevelEnum.ZONE.getLevel().equals(immediateUser.getProfitLevel())){
                        UserDistConfigDto zoneAgent = getUserDistConfigDto(immediateUser, zoneRate.add(storeRate).setScale(2), DistTypeEnum.AGENT_ITEM_PROFIT);
                        userDistConfigDtos.add(zoneAgent);
                    }
                }
            }
        }
    }

    private void perfectingDistConfig(List<UserDistConfigDto> userDistConfigDtos, UserVo userVo, Map<String, String> settingMap,int deep) {
        if (deep > 2) {
            return;
        }
        if (StringUtils.hasText(userVo.getImmediateSuperior())) {
            UserVo immediateUser = userApi.getUserById(userVo.getImmediateSuperior()).getResult();
            if (null != immediateUser) {
                perfectingDistConfig(userDistConfigDtos,immediateUser,settingMap,deep++);
            }
        }
        UserEnum.ProfitLevelEnum level = UserEnum.ProfitLevelEnum.getLevel(userVo.getProfitLevel());
        String s = settingMap.get(level.getProfitName());
        if (StringUtils.hasText(s)){
            BigDecimal rate = new BigDecimal(s);
            UserDistConfigDto agent = getUserDistConfigDto(userVo, rate, DistTypeEnum.AGENT_ITEM_PROFIT);
            userDistConfigDtos.add(agent);
        }
    }

    public PageVo<DistOrderVo> subAgentPage(PageBo<SubAgentDistOrderBo> pageBo) {
        PageHelper.startPage(pageBo.getPage(), pageBo.getPageSize(), MySqlUtil.orderBy(pageBo.getSort(), false));
        PageInfo<String> orderIdInfo = new PageInfo(orderDao.distOrderGroupByOrderId(pageBo.getParam()));
        List<DistOrderVo> list = new ArrayList<>();
        if (null != orderIdInfo && !CollectionUtils.isEmpty(orderIdInfo.getList())) {
            List<DistOrder>  orderVos = orderDao.querySubAgentDistOrder(pageBo.getParam(),orderIdInfo.getList());
            orderVos.forEach(o -> {
                DistOrderVo distOrderVo = list.stream().filter(vo -> o.getOrderId().equals(vo.getOrderId())).findFirst().orElse(null);
                if (null == distOrderVo) {
                    distOrderVo = BeanConverUtils.convertBean(o, DistOrderVo.class);
                    distOrderVo.setTradeAmount(BigDecimal.ZERO);
                    list.add(distOrderVo);
                }
                BigDecimal tradeAmount = distOrderVo.getTradeAmount();
                tradeAmount = tradeAmount.add(o.getDistAmount());
                distOrderVo.setTradeAmount(tradeAmount);
            });
        }
        return new PageVo<>(orderIdInfo.getTotal(), pageBo.getPage(), pageBo.getPageSize(), list);
    }

    public List<AgentDistStatisticsDto> getAgentDistStatistics(String distUserId, List<String> sources) {
        return orderDao.getAgentDistStatistics(distUserId,sources);
    }

}
